<template>
	<view class="container">
		<view class="loading" v-if="isLoading">
			<view class="loading-spinner"></view>
			<text class="loading-text">加载中...</text>
		</view>

		<view class="content" v-else>
			<view class="header">
				<text class="title">入党申请书审核</text>
				<text class="subtitle">请认真审核入党申请书</text>
			</view>

			<view class="list-container">
				<view class="list-item" v-for="(item, index) in applicationList" :key="index">
					<view class="item-header">
						<view class="header-left">
							<text class="applicant-name">{{item.name}}</text>
							<text
								:class="['status-tag', getStatusClass(item.status)]">{{getStatusText(item.status)}}</text>
						</view>
						<text class="apply-time">{{formatDate(item.applyDate)}}</text>
					</view>
					<view class="item-content">
						<text class="content-text">{{item.selfIntro}}</text>
					</view>
					<view class="item-footer">
						<button class="action-btn view" @tap="showDetail(item)">查看</button>
						<template v-if="item.status === 0">
							<button class="action-btn approve" @tap="approveApplication(item)">通过</button>
							<button class="action-btn reject" @tap="rejectApplication(item)">拒绝</button>
						</template>
					</view>
				</view>

				<view class="empty-tip" v-if="applicationList.length === 0">
					<text>暂无待审核的入党申请书</text>
				</view>
			</view>
		</view>

		<!-- 详情弹窗 -->
		<view class="detail-popup" v-if="showPopup" @tap.stop="closePopup">
			<view class="popup-mask"></view>
			<view class="popup-content" @tap.stop>
				<view class="popup-header">
					<text class="popup-title">入党申请书详情</text>
					<text class="close-btn" @tap="closePopup">×</text>
				</view>
				<scroll-view 
					class="popup-body" 
					scroll-y 
					:style="{ maxHeight: 'calc(80vh - 100rpx)' }"
					:scroll-top="scrollTop"
					@scroll="handleScroll"
				>
					<view class="detail-section">
						<view class="section-title">基本信息</view>
						<view class="detail-grid">
							<view class="detail-item">
								<text class="detail-label">姓名</text>
								<text class="detail-value">{{currentDetail.name}}</text>
							</view>
							<view class="detail-item">
								<text class="detail-label">性别</text>
								<text class="detail-value">{{currentDetail.gender}}</text>
							</view>
							<view class="detail-item">
								<text class="detail-label">出生日期</text>
								<text class="detail-value">{{formatDate(currentDetail.birthdate)}}</text>
							</view>
							<view class="detail-item">
								<text class="detail-label">联系电话</text>
								<text class="detail-value">{{currentDetail.phoneNum}}</text>
							</view>
							<view class="detail-item">
								<text class="detail-label">民族</text>
								<text class="detail-value">{{currentDetail.ethnicity}}</text>
							</view>
							<view class="detail-item">
								<text class="detail-label">学历</text>
								<text class="detail-value">{{currentDetail.eduLevel}}</text>
							</view>
							<view class="detail-item">
								<text class="detail-label">所属学院</text>
								<text class="detail-value">{{currentDetail.department}}</text>
							</view>
							<view class="detail-item">
								<text class="detail-label">申请日期</text>
								<text class="detail-value">{{formatDate(currentDetail.applyDate)}}</text>
							</view>
							<view class="detail-item">
								<text class="detail-label">当前状态</text>
								<text
									:class="['detail-value', getStatusClass(currentDetail.status)]">{{getStatusText(currentDetail.status)}}</text>
							</view>
						</view>
					</view>

					<view class="detail-section">
						<view class="section-title">申请书内容</view>
						<view class="detail-item full-width">
							<text class="detail-content" style="white-space: pre-wrap; word-break: break-all;">{{currentDetail.selfIntro}}</text>
						</view>
					</view>

					<view class="detail-section" v-if="currentDetail.handwrittenDoc">
						<view class="section-title">手写申请书</view>
						<view class="file-item" @tap="downloadFile(currentDetail.handwrittenDoc)">
							<view class="file-icon">
								<text class="iconfont icon-file"></text>
							</view>
							<view class="file-info">
								<text class="file-name">{{getFileName(currentDetail.handwrittenDoc)}}</text>
								<text class="file-tip">点击下载查看</text>
							</view>
							<text class="download-icon">↓</text>
						</view>
					</view>
					<view style="height: 40rpx;"></view>
				</scroll-view>
			</view>
		</view>

		<!-- 审核意见弹窗 -->
		<view class="audit-popup" v-if="showAuditPopup" @tap.stop="closeAuditPopup">
			<view class="popup-mask"></view>
			<view class="popup-content" @tap.stop>
				<view class="popup-header">
					<text class="popup-title">{{auditType === 'approve' ? '通过审核' : '拒绝审核'}}</text>
					<text class="close-btn" @tap="closeAuditPopup">×</text>
				</view>
				<view class="popup-body">
					<view class="form-item">
						<text class="label required">审核意见</text>
						<textarea class="audit-textarea" v-model="auditComment" placeholder="请输入审核意见"
							maxlength="200"></textarea>
						<text class="word-count">{{auditComment.length}}/200</text>
					</view>
					<view class="popup-footer">
						<button class="cancel-btn" @tap="closeAuditPopup">取消</button>
						<button class="confirm-btn" @tap="confirmAudit">确定</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue'
	import {
		getApplicationList,
		getDeptUsers,
		saveApplication,
		userInfo
	} from '@/common/js/api.js'

	// 加载状态
	const isLoading = ref(true)
	const applicationList = ref([])
	const userId = uni.getStorageSync("userId");

	// 弹窗相关
	const showPopup = ref(false)
	const currentDetail = ref({})

	// 审核相关
	const showAuditPopup = ref(false)
	const auditType = ref('')
	const auditComment = ref('')
	const currentItem = ref(null)

	// 滚动相关
	const scrollTop = ref(0)

	// 处理滚动
	const handleScroll = (e) => {
		scrollTop.value = e.detail.scrollTop
	}

	// 获取申请书列表
	const getList = async () => {
		try {
			const res_user = await getDeptUsers(userId);
			if (res_user.code === 200) {
				const useridList = ref([]);
				for (var i = 0; i < res_user.data.sameDeptPeople.length; ++i) {
					useridList.value.push(res_user.data.sameDeptPeople[i].id);
				}
				// 获取所有的入党申请书
				const res_application = await getApplicationList();
				if (res_application.code == 200) {
					const ori_list = res_application.data.page.records;
					for (var i = 0; i < ori_list.length; ++i) {
						if (useridList.value.includes(ori_list[i].userId)) {
							const res = await userInfo(ori_list[i].userId);
							ori_list[i].name = res.name;
							applicationList.value.push(ori_list[i]);
						}
					}
				}
				console.log(applicationList.value);
			} else {
				wx.showToast({
					title: '获取列表失败',
					icon: 'none'
				})
			}
		} catch (error) {
			wx.showToast({
				title: '获取列表失败',
				icon: 'none'
			});
			console.log(error);
		}
	}

	// 格式化日期
	const formatDate = (dateStr) => {
		const date = new Date(dateStr)
		const year = date.getFullYear()
		const month = String(date.getMonth() + 1).padStart(2, '0')
		const day = String(date.getDate()).padStart(2, '0')
		return `${year}-${month}-${day}`
	}

	// 获取状态文本
	const getStatusText = (status) => {
		const statusMap = {
			0: '待审核',
			1: '已通过',
			2: '已拒绝'
		}
		return statusMap[status] || '未知状态'
	}

	// 获取状态样式类
	const getStatusClass = (status) => {
		const classMap = {
			0: 'status-pending',
			1: 'status-approved',
			2: 'status-rejected'
		}
		return classMap[status] || ''
	}

	// 显示详情
	const showDetail = (item) => {
		currentDetail.value = item
		showPopup.value = true
	}

	// 关闭弹窗
	const closePopup = () => {
		showPopup.value = false
	}

	// 下载文件
	const downloadFile = (url) => {
		uni.showLoading({
			title: '下载中...'
		})
		console.log(url);
		const urls = url.split(',');

		uni.downloadFile({
			url: urls[0],
			success: (res) => {
				console.log(res);
				if (res.statusCode === 200) {
					uni.openDocument({
						filePath: res.tempFilePath,
						success: () => {
							console.log('打开文档成功')
						},
						fail: () => {
							uni.showToast({
								title: '打开文件失败',
								icon: 'none'
							})
						}
					})
				} else {
					uni.showToast({
						title: '下载失败',
						icon: 'none'
					})
				}
			},
			fail: () => {
				uni.showToast({
					title: '下载失败',
					icon: 'none'
				})
			},
			complete: () => {
				uni.hideLoading()
			}
		})
	}

	// 从URL中获取文件名
	const getFileName = (url) => {
		if (!url) return '未知文件'
		const urls = url.split(',')
		const lastUrl = urls[0]
		const fileName = lastUrl.split('/').pop()
		return fileName || '未知文件'
	}

	// 显示审核弹窗
	const showAuditForm = (type, item) => {
		auditType.value = type
		currentItem.value = item
		console.log(currentItem.value);
		auditComment.value = ''
		showAuditPopup.value = true
	}

	// 关闭审核弹窗
	const closeAuditPopup = () => {
		showAuditPopup.value = false
		auditComment.value = ''
	}

	// 确认审核
	const confirmAudit = async () => {
		if (!auditComment.value.trim()) {
			uni.showToast({
				title: '请输入审核意见',
				icon: 'none'
			})
			return
		}

		try {
			currentItem.value.review = auditComment.value;
			// 获取当前时间，格式化为符合Java LocalDateTime要求的格式 (yyyy-MM-dd HH:mm:ss)
			const now = new Date();
			const year = now.getFullYear();
			const month = String(now.getMonth() + 1).padStart(2, '0');
			const day = String(now.getDate()).padStart(2, '0');
			const hours = String(now.getHours()).padStart(2, '0');
			const minutes = String(now.getMinutes()).padStart(2, '0');
			const seconds = String(now.getSeconds()).padStart(2, '0');
			const currentTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			currentItem.value.reviewTime = currentTime;
			if (auditType.value === 'approve') {
				currentItem.value.status = 1;
			} else {
				currentItem.value.status = 2;
			}
			
			const result = await saveApplication(currentItem.value);

			if (result.code == 200) {
				uni.showToast({
					title: auditType.value === 'approve' ? '已通过' : '已拒绝',
					icon: 'success'
				})
				closeAuditPopup()
			} else {
				uni.showToast({
					title: result.message || '操作失败',
					icon: 'none'
				})
			}
		} catch (error) {
			uni.showToast({
				title: '操作失败',
				icon: 'none'
			})
			console.log(error);
		}
	}

	// 修改原有的通过和拒绝方法
	const approveApplication = (item) => {
		showAuditForm('approve', item)
	}

	const rejectApplication = (item) => {
		showAuditForm('reject', item)
	}

	// 生命周期钩子
	onMounted(async () => {
		try {
			await getList()
		} finally {
			setTimeout(() => {
				isLoading.value = false
			}, 300)
		}
	})
</script>

<style lang="scss" scoped>
	.container {
		padding: 30rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
		box-sizing: border-box;
		position: relative;
	}

	.loading {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: #fff;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		z-index: 999;
	}

	.loading-spinner {
		width: 80rpx;
		height: 80rpx;
		border: 6rpx solid #f3f3f3;
		border-top: 6rpx solid #ff7a45;
		border-radius: 50%;
		animation: spin 1s linear infinite;
		margin-bottom: 20rpx;
	}

	.loading-text {
		font-size: 28rpx;
		color: #666;
	}

	@keyframes spin {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}

	.header {
		background-color: #fff;
		padding: 40rpx 30rpx;
		margin-bottom: 30rpx;
		border-radius: 16rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

		.title {
			font-size: 40rpx;
			font-weight: bold;
			color: #333;
			display: block;
			margin-bottom: 16rpx;
		}

		.subtitle {
			font-size: 28rpx;
			color: #666;
		}
	}

	.list-container {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 30rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
	}

	.list-item {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 24rpx;
		margin-bottom: 24rpx;
		border: 2rpx solid #eee;

		&:last-child {
			margin-bottom: 0;
		}
	}

	.item-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 16rpx;
	}

	.header-left {
		display: flex;
		align-items: center;
		gap: 16rpx;
	}

	.applicant-name {
		font-size: 32rpx;
		font-weight: 500;
		color: #333;
	}

	.apply-time {
		font-size: 24rpx;
		color: #999;
	}

	.item-content {
		margin-bottom: 24rpx;
	}

	.content-text {
		font-size: 28rpx;
		color: #666;
		line-height: 1.6;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
	}

	.item-footer {
		display: flex;
		justify-content: flex-end;
		gap: 20rpx;
	}

	.action-btn {
		margin: 0;
		padding: 0 32rpx;
		height: 64rpx;
		line-height: 64rpx;
		font-size: 28rpx;
		border-radius: 32rpx;

		&.view {
			background-color: #f8f8f8;
			color: #666;
		}

		&.approve {
			background-color: #52c41a;
			color: #fff;
		}

		&.reject {
			background-color: #ff4d4f;
			color: #fff;
		}

		&:active {
			opacity: 0.8;
		}
	}

	.empty-tip {
		text-align: center;
		padding: 60rpx 0;
		color: #999;
		font-size: 28rpx;
	}

	.status-tag {
		padding: 4rpx 16rpx;
		border-radius: 24rpx;
		font-size: 24rpx;

		&.status-pending {
			background-color: #e6f7ff;
			color: #1890ff;
		}

		&.status-approved {
			background-color: #f6ffed;
			color: #52c41a;
		}

		&.status-rejected {
			background-color: #fff2f0;
			color: #ff4d4f;
		}
	}

	.detail-popup {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 999;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.popup-mask {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.6);
	}

	.popup-content {
		position: relative;
		width: 90%;
		max-height: 80vh;
		background-color: #fff;
		border-radius: 16rpx;
		overflow: hidden;
		z-index: 1000;
		display: flex;
		flex-direction: column;
	}

	.popup-header {
		padding: 30rpx;
		border-bottom: 2rpx solid #eee;
		display: flex;
		justify-content: space-between;
		align-items: center;
		flex-shrink: 0;
	}

	.popup-title {
		font-size: 32rpx;
		font-weight: 500;
		color: #333;
	}

	.close-btn {
		font-size: 40rpx;
		color: #999;
		padding: 0 20rpx;
	}

	.popup-body {
		flex: 1;
		overflow-y: auto;
		-webkit-overflow-scrolling: touch;
		padding: 30rpx;
	}

	.detail-section {
		margin-bottom: 40rpx;

		&:last-child {
			margin-bottom: 0;
		}
	}

	.section-title {
		font-size: 32rpx;
		font-weight: 500;
		color: #333;
		margin-bottom: 24rpx;
		padding-left: 24rpx;
		border-left: 8rpx solid #ff7a45;
	}

	.detail-grid {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 24rpx;
	}

	.detail-item {
		margin-bottom: 0;
	}

	.detail-label {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 8rpx;
		display: block;
	}

	.detail-value {
		font-size: 30rpx;
		color: #333;
		word-break: break-all;

		&.status-pending {
			color: #1890ff;
		}

		&.status-approved {
			color: #52c41a;
		}

		&.status-rejected {
			color: #ff4d4f;
		}
	}

	.detail-content {
		font-size: 30rpx;
		color: #333;
		line-height: 1.6;
		background-color: #f8f8f8;
		padding: 24rpx;
		border-radius: 12rpx;
		width: 100%;
		box-sizing: border-box;
		display: block;
	}

	.file-item {
		display: flex;
		align-items: center;
		padding: 24rpx;
		background-color: #f8f8f8;
		border-radius: 12rpx;

		&:active {
			background-color: #f0f0f0;
		}
	}

	.file-icon {
		width: 80rpx;
		height: 80rpx;
		background-color: #ff7a45;
		border-radius: 12rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 24rpx;

		.iconfont {
			font-size: 48rpx;
			color: #fff;
		}
	}

	.file-info {
		flex: 1;
		overflow: hidden;
	}

	.file-name {
		font-size: 30rpx;
		color: #333;
		display: block;
		margin-bottom: 8rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.file-tip {
		font-size: 24rpx;
		color: #999;
	}

	.download-icon {
		font-size: 40rpx;
		color: #999;
		margin-left: 24rpx;
	}

	.audit-popup {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 999;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.form-item {
		margin-bottom: 30rpx;
	}

	.label {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 16rpx;
		display: block;

		&.required::before {
			content: '*';
			color: #ff4d4f;
			margin-right: 4rpx;
		}
	}

	.audit-textarea {
		width: 100%;
		height: 240rpx;
		background-color: #f8f8f8;
		border-radius: 12rpx;
		padding: 24rpx;
		font-size: 30rpx;
		box-sizing: border-box;
		line-height: 1.5;
	}

	.word-count {
		font-size: 24rpx;
		color: #999;
		text-align: right;
		margin-top: 12rpx;
		display: block;
	}

	.popup-footer {
		display: flex;
		justify-content: flex-end;
		gap: 24rpx;
		margin-top: 40rpx;
	}

	.cancel-btn {
		margin: 0;
		padding: 0 32rpx;
		height: 72rpx;
		line-height: 72rpx;
		font-size: 28rpx;
		border-radius: 36rpx;
		background-color: #f5f5f5;
		color: #666;
	}

	.confirm-btn {
		margin: 0;
		padding: 0 32rpx;
		height: 72rpx;
		line-height: 72rpx;
		font-size: 28rpx;
		border-radius: 36rpx;
		background-color: #ff7a45;
		color: #fff;

		&:active {
			opacity: 0.9;
		}
	}
</style>